import { Button, Form, Input , Table, message } from "antd";
import { useEffect, useMemo, useState } from "react";
import './index.css';
import { ColumnsType } from "antd/es/table";
import { useForm } from "antd/es/form/Form";
import { userFriendshipServer } from "@/servers/userServer";
import { AddFriendModal } from "./addFriendModal";
import { AddListModal } from "./addListModal";
import { createOneChatServer, foundChatServcer } from "@/servers/chatroomServer";
import { useNavigate } from "react-router-dom";

interface SearchFriend {
    name: string;
}

export interface FriendshipSearchResult {
    id: number;
    username: string;
    nickName: string;
    headPic: string;
    email: string;
    isJoin?:boolean
}

export default function Friendship() {
    const [friendshipResult, setFriendshipResult] = useState<Array<FriendshipSearchResult>>([]);
    const [isAddFriendModalOpen, setAddFriendModalOpen] = useState(false);
    const [isAddListModalOpen, setAddListModalOpen] = useState(false);
    const [num , setNum] = useState(0)

    const navigate = useNavigate()
    const gotoChat = async (friendId:number) => {
        const res = await foundChatServcer(friendId)
        const {code , data} = res.data
        console.log(code , data);
        if(data){
            navigate('/chat' , {
                state:{
                    chatroomId:data
                }
            })
        }else{
            const res = await createOneChatServer(friendId)
            const { code , data } = res.data
            if(code === 200 || code === 201){
                navigate('/chat' , {
                    state:{
                        chatroomId:data.chatroomId
                    }
                })
            }
        }
    }


    const columns: ColumnsType<FriendshipSearchResult> = useMemo(() => [
        {
            title: '昵称',
            dataIndex: 'nickName'
        },
        {
            title: '头像',
            dataIndex: 'headPic',
            render: (_, record) => (
                <div>
                    <img src={record.headPic}/>
                </div>
            )
        },
        {
            title: '邮箱',
            dataIndex: 'email'
        },
        {
            title: '操作',
            render: (_, record) => (
                <div>
                    <Button onClick={()=> gotoChat(record.id)}>聊天 </Button>
                </div>
            )
        }
    ], []);

    const searchFriend = async (values: SearchFriend) => {
        getUserFriendship(values.name)
    };


    const getUserFriendship = async (name:string) => {
        const res = await userFriendshipServer(name)
        const {code , data  , message:msg} = res.data
        if(code === 200 || code === 201){
            setFriendshipResult(data)
        }else{
            message.error(msg)
        }
    }

    const [form ]  = useForm();

    useEffect(() => {
        searchFriend({
            name: form.getFieldValue('name')
        });
    }, [num]);


    return <div id="friendship-container">
        <div className="friendship-form">
            <Form
                form={form}
                onFinish={searchFriend}
                name="search"
                layout='inline'
                colon={false}
            >
                <Form.Item label="昵称" name="name">
                    <Input />
                </Form.Item>

                <Form.Item label=" ">
                    <Button type="primary" htmlType="submit">
                        搜索
                    </Button>
                </Form.Item>
                <Form.Item label=" ">
                    <Button type="primary" style={{background: 'green'}} onClick={() => setAddFriendModalOpen(true)}>
                        添加好友
                    </Button>
                </Form.Item>
                <Form.Item label=" ">
                    <Button type="primary" style={{background: 'pink'}} onClick={() => setAddListModalOpen(true)}>
                        好友申请列表
                    </Button>
                </Form.Item>
            </Form>
        </div>
        <div className="friendship-table">
            <Table columns={columns} dataSource={friendshipResult} rowKey={(record) => record.id}  style={{width: '1000px'}}/>
        </div>
        <AddFriendModal isOpen={isAddFriendModalOpen} handleClose={()=>{
            setAddFriendModalOpen(false)
        }} />
        <AddListModal 
            isOpen={isAddListModalOpen} 
            handleClose={()=>{setAddListModalOpen(false)}}
            refreshNum={()=>{setNum(Math.random())}}
        />
    </div>
}